<template>
  <div class="container">
    <el-form ref="formRef" :model="form" :rules="rules" v-loading="loading" label-width="150px">
      <el-divider content-position="left"><span class="title-left-color">基本信息</span></el-divider>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="模板名称：" prop="name">
            <el-input v-model.trim="form.name" placeholder="请填写回收类型"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="排序：" prop="sort">
            <el-input v-model.number="form.sort" placeholder="请填写排序"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="10">
          <el-form-item label="子标题：" prop="title">
            <el-input v-model.trim="form.title" placeholder="请填写子标题"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="子描述：" prop="description">
            <el-input v-model.trim.number="form.description" placeholder="请填写子描述"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="5">
          <el-form-item label="是否查询条件：" prop="is_header">
            <el-switch v-model="form.is_header" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="是否查询显示：" prop="is_search">
            <el-switch v-model="form.is_search" :active-value="1" :inactive-value="0" active-text="显示" inactive-text="隐藏"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left"><span class="title-left-color">子分类信息</span></el-divider>
      <div class="handle-box mb10">
        <el-button type="primary" :icon="Plus" :disabled="disabledbtn" @click="handleAddChildrenList">新增</el-button>
        <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="batchDelete">
          <template #reference>
            <el-button type="danger" :icon="Delete" :disabled="disabledbtn">批量删除</el-button>
          </template>
        </el-popconfirm>
      </div>
      <el-table :data="form.children" border class="table" ref="childRef" :reserve-selection="true">
        <el-table-column type="index" align="center"> </el-table-column>
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="name" label="子类名称" align="center">
          <template #default="scope">
            <el-input v-model.trim="scope.row.name" placeholder="请输入内容"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" align="center">
          <template #default="scope">
            <el-input v-model.number="scope.row.sort" placeholder="请输入内容" @change="handleLocalSort"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="image" label="描述图片" align="center">
          <template #default="scope: { row: IRecoveryTypeChild }">
            <UploadImageInfo :imageWidth="300" :imageHeight="78" :limit="300" suggestInfo="" v-model:disabledbtn="disabledbtn" v-model:loading="loading" imageKey="image" v-model:form="scope.row" isCenter />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <div class="mlr10 display-inline-block">
              <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="deleteInfo([scope.row.uniqueId])">
                <template #reference>
                  <el-button link :icon="Delete" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <div class="footer-center">
      <el-button :disabled="disabledbtn" @click="cancelSubmit">取 消</el-button>
      <el-button type="primary" :disabled="disabledbtn" v-if="!isDisabledbtn" @click="submitForm">确 定</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import UploadImageInfo from "@/components/common/UploadImageInfo.vue";
import { Delete, Plus } from "@element-plus/icons-vue";
import type { postOrPutType } from "@/constants";
import type { HasId, ViewMode } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IRecoveryType, IRecoveryTypeChild } from "@/types/recoveryManage/recoveryType";
import { commonRecycleTypeInfo, getRecycleTypeByIdInfo } from "@/utils/api/recycleType";
const { disabledbtn, loading, toggleState } = useState();
interface Props {
  id: number;
}
const { id } = defineProps<Props>();
const formStatus = defineModel<ViewMode>("formStatus", { required: true });

const emit = defineEmits<{
  handleInitData: [];
  handleSuccess: [];
}>();

const isDisabledbtn = ref(false);
const formRef = useTemplateRef("formRef");
const childRef = useTemplateRef("childRef");
const methodType = ref<postOrPutType>("PUT");
const form = reactive<IRecoveryType>({
  id: 0,
  name: "",
  sort: 0,
  is_search: 0,
  is_header: 0,
  title: "",
  description: "",
  create_time: 0,
  children: []
});
const rules = reactive({
  name: [{ required: true, message: "请填写回收类型", trigger: "blur" }],
  sort: [{ required: true, message: "请填写排序顺序", trigger: "blur" }]
});

onMounted(() => {
  console.log("Component mounted!");
});

/* formStatus处理器 */
const statusHandlers: Record<ViewMode, () => void> = {
  view: () => {
    isDisabledbtn.value = true;
  },
  edit: () => {
    methodType.value = "PUT";
  },
  add: () => {
    methodType.value = "POST";
  },
  none: () => {
    /* 初始化数据 */
    handleInitData();
  }
};
/* 监听formStatus,新增，编辑，查看的时候都可以打开模态框，又是有不同的操作和效果，需要单独判断，none为模态框关闭的情况，需要初始化数据 */
watch(formStatus, newValue => {
  const handler = statusHandlers[newValue];
  handler?.();
});
/*  */
watch(
  () => id,
  newValue => {
    if (newValue == 0) {
      /* 初始化数据 */
    } else {
      form.id = newValue;
      handleRecycleTypeByIdInfo(id);
    }
  }
);

/* 获取详情信息 */
function handleRecycleTypeByIdInfo(id: number) {
  toggleState(true);
  getRecycleTypeByIdInfo<IRecoveryType, HasId>({ id })
    .then(res => {
      form.id = res.result.id;
      form.name = res.result.name;
      form.sort = res.result.sort;
      form.is_search = res.result.is_search;
      form.is_header = res.result.is_header;
      form.title = res.result.title;
      form.description = res.result.description;
      res.result.children.forEach(item => {
        item.uniqueId = item.id;
      });
      form.children = res.result.children;
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}

/* 初始化数据 */
function handleInitData() {
  methodType.value = "POST";
  isDisabledbtn.value = false;

  form.id = 0;
  form.children = [];
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
}

/* 保存或编辑 */
function submitForm() {
  if (!formRef.value) return;
  formRef.value.validate(valid => {
    if (!valid) {
      ElMessage.warning("请填写必填字段");
      return;
    }
    submitFormInfo();
  });
}

/* 保存或编辑信息 */
function submitFormInfo() {
  /* 防止多次提交 */
  toggleState(true);
  commonRecycleTypeInfo(form, methodType.value)
    .then(res => {
      ElMessage.success(res.msg);
      cancelSubmit();
      emit("handleSuccess");
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 保存或编辑 取消提交 */
function cancelSubmit() {
  // clearData();
  // activeName = "one";
  emit("handleInitData");
}

/* 现在子类信息 */
function handleAddChildrenList() {
  form.children.push({
    id: 0,
    /* 如果后端做了id小于等于0 的数据为保存的，那么就不需要这个字段了 */
    uniqueId: -new Date().getTime(),
    name: "",
    image: "",
    sort: 0
  });
}

/* 批量删除 */
function batchDelete() {
  /* 获取选中的数据 */
  let selection = childRef.value!.store.states.selection.value;
  if (selection.length === 0) {
    ElMessage.warning("请至少选择一条数据");
    return;
  }
  let idArray: number[] = [];
  for (const item of selection) {
    idArray.push(item.uniqueId);
  }
  deleteInfo(idArray);
}
/* 删除后的信息 */
function deleteInfo(idArray: Array<number>) {
  /* 当删除成功后，删除对应选中的数据或单个数据 */
  form.children = form.children.filter((item: IRecoveryTypeChild) => !idArray.includes(item.uniqueId));
}
/* 本地商品排序 */
function handleLocalSort() {
  form.children.sort((a, b) => b.sort - a.sort);
}
</script>

<style lang="scss" scoped>
/* 修改select的盒模型 */
.el-select {
  display: block;
}
/* 底部按钮居中 */
.footer-center {
  margin: 10px 0;
  text-align: center;
}
</style>
